package com.notary.controller;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.notary.entity.vo.JsonResult;
import com.notary.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Api(tags = "文件上传")
@RestController
public class UploadController {

	@Autowired
	private OSS ossClient;

	@Value("${aliyun.bucketName}")
	private String bucketName;
	
	@Value("${aliyun.urlPrefix}")
	private String urlPrefix;

	@Value("${aliyun.folderName}")
	private String folderName;

	@ApiOperation(value = "上传材料")
	@PostMapping(value = "uploadFile")
	public JsonResult uploadFile(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String md5File="";
		String key = folderName+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss"))+ "/" // 时间戳 文件目录
				+ UUID.randomUUID().toString().replaceAll("-", "") // uuid 生成文件名
				+ fileName.substring(fileName.lastIndexOf(".")); // 文件后缀1
		try {
			 ossClient.putObject(bucketName, key, file.getInputStream());
			 md5File= MD5Utils.MD5Hash(file.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.fail("9999","上传失败");
		}
		JSONObject object=new JSONObject();
		object.put("urf",urlPrefix + key);
		object.put("md5",md5File);
		return JsonResult.success(object);
	}






}